<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/9
 * Time: 20:41
 */

namespace app\admin\model;

use think\Model;
use think\db;

class MemberModel extends Model
{
    public function updateById($id, $data)
    {
        return $this->where(['id' => $id])->update($data);
    }

    /**
     * 列表，关联本表获取父亲名字
     * @return array
     */
    public function listing($condition)
    {
        $condition['m.is_deleted'] = 0;
        return Db::name('member')
            ->alias('m')
            ->join('member fm', 'fm.id=m.parent_id', 'LEFT')
            ->join('member hm', 'hm.id=m.spouse_id', 'LEFT')
            ->join('clan c', 'c.id=m.clan_id', 'LEFT')
            ->where($condition)
            ->field('m.*,fm.name as father_name,c.name as clan_name,hm.name as husband_name');

    }

    /**
     * 本族成员列表
     */
    public function memberList($name, $clan_id)
    {
        $where = ['generation' => ['gt', 0], 'm.is_deleted' => 0];
        if ($name) {
            $where['m.name'] = ['like', '%' . $name . '%'];
        }
        if($clan_id){
            $where['m.clan_id'] = $clan_id;
        }
        return Db::name('member')
            ->alias('m')
            ->join('clan c', 'c.id=m.clan_id', 'LEFT')
            ->where($where)
            ->field('m.*,c.name as clan_name')
            ->select()
            ->toArray();
    }

    /**
     * 关系链
     */
    public function relationChan($id,$return = array())
    {
        if(!$return){
            $return[] = $id;
        }
        $res = $this->where(['id'=>$id,'is_deleted'=>0])->find()->toArray();
        if($res['parent_id']){
            $return[] = $res['parent_id'];
            $return = $this->relationChan($res['parent_id'],$return);
        }
        return $return;
    }

    /**
     * 循环的删除,删除本人及其所有子女老婆
     */
    public function cyclicDelete($id)
    {
        $data = $this->where(['id'=>$id,'is_deleted'=>0])->find();
        if($data){
            $data = $data->toArray();
            $this->where(['id'=>$id,'is_deleted'=>0])->update(['update_time'=>time(),'is_deleted'=>1]);
            //删除他的老婆们
            $this->where(['spouse_id'=>$id,'is_deleted'=>0])->update(['update_time'=>time(),'is_deleted'=>1]);
            $children = $this->where(['parent_id'=>$data['id'],'is_deleted'=>0])->select();
            if($children){
                $children = $children->toArray();
                foreach ($children as $child) {
                    $this->cyclicDelete($child['id']);
                }
            }
        }
    }


}